//
//  OpFlashDeliverMarketController.m
//  LoveFreshBeeProject
//
//  Created by skywalker on 16/12/31.
//  Copyright © 2016年 斯芬克斯. All rights reserved.
//

#import "OpFlashDeliverMarketController.h"
#import <Masonry.h>
#import <MBProgressHUD.h>
#import "FoodModel.h"
#import "FoodDetailModel.h"
#import "FoodTableViewCell.h"
#import "CZAdditions.h"
#import "FoodDetailTableViewCell.h"
static NSString * foodCategroyCellID = @"foodCategroyCellID";
static NSString * foodCellID = @"foodCellID";
@interface OpFlashDeliverMarketController ()<UITableViewDelegate,UITableViewDataSource,FoodDetailTableViewCellDelegate,CAAnimationDelegate>
@property (nonatomic,weak) UITableView * foodCategroyView;//左边

@property (nonatomic,weak) UITableView * foodView;//右边

@property (nonatomic, strong) NSIndexPath *leftSelectedIndexPath;
@property (nonatomic, assign) int flag;
@property (nonatomic, strong) UIVisualEffectView *effectView;
@end

@implementation OpFlashDeliverMarketController{
    NSArray *_newsList;
    NSDictionary *_dataDict;
    NSDictionary *_newsData;
    
}
- (void)loadData{
    NSString *url = @"http://iosapi.itcast.cn/loveBeen/supermarket.json.php";
    NSDictionary *parameters = [NSDictionary dictionaryWithObject:@"5" forKey:@"call"];
    [FoodModel loadNewsDataWithUrlStr:url parameters:parameters complete:^(NSDictionary *dataDict) {
        _dataDict = dataDict;
        
    } success:^(NSArray *newsList) {
        _newsList = newsList;
        [self.foodCategroyView reloadData];
        [FoodDetailModel loadNewsDataWithDataDict:_dataDict dataArr:newsList success:^(NSDictionary *newsDict) {
            _newsData = newsDict;
            [self.foodView reloadData];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            //让左边表中选中第0组第0行
            [self.foodCategroyView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
            [self.effectView removeFromSuperview];
        }];
        
    } failed:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.flag = 0;
    [self loadData];
    UITableView *foodCategroyView = [[UITableView alloc] init];
    //设置数据源和代理
    foodCategroyView.delegate = self;
    foodCategroyView.dataSource = self;
    //设置行高
    foodCategroyView.rowHeight = 50;
    foodCategroyView.showsVerticalScrollIndicator = NO;
    // 清空分割线的内边距
    foodCategroyView.separatorInset = UIEdgeInsetsZero;
    //注册单元格
    [foodCategroyView registerClass:[FoodTableViewCell class] forCellReuseIdentifier:foodCategroyCellID];
    [self.view addSubview:foodCategroyView];
    UITableView *foodView = [[UITableView alloc] init];
    //设置数据源和代理
    foodView.delegate = self;
    foodView.dataSource = self;
    //自适应行高
    foodView.rowHeight = UITableViewAutomaticDimension;
    foodView.estimatedRowHeight = 120;
    // 清空分割线的内边距
    foodView.separatorInset = UIEdgeInsetsZero;
    //注册单元格
    [foodView registerNib:[UINib nibWithNibName:@"FoodDetailTableViewCell" bundle:nil] forCellReuseIdentifier:foodCellID];
    [self.view addSubview:foodView];
    //布局
    [foodCategroyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.equalTo(self.view);
        make.width.offset(self.view.bounds.size.width * 0.25);
        
    }];
    [foodView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.equalTo(self.view);
        make.width.offset(self.view.bounds.size.width * 0.75);
        make.bottom.offset(-49);
    }];
    //赋值
    self.foodCategroyView = foodCategroyView;
    self.foodView = foodView;
    UIBlurEffect *beffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc]initWithEffect:beffect];
    effectView.frame = self.view.bounds;
    [self.view addSubview:effectView];
    self.effectView = effectView;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载";
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (tableView == self.foodCategroyView) {
        return 1;
    }
    return _newsList.count;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.foodCategroyView) {
        return _newsList.count;
    }
    FoodModel *fModel = _newsList[section];
    NSArray *arr = _newsData[fModel.id];
    return arr.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.foodCategroyView) {
        FoodTableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:foodCategroyCellID forIndexPath:indexPath];
        FoodModel *model = _newsList[indexPath.row];
        cell.title =model.name;
        return cell;
    }
    
    FoodDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:foodCellID forIndexPath:indexPath];
    FoodModel *models = _newsList[indexPath.section];
    NSArray *arrData = _newsData[models.id];
    FoodDetailModel *detail = arrData[indexPath.row];
    cell.detailModel = detail;
    cell.delegate = self;
    return cell;
}
//实现代理方法
- (void)foodDetailTableViewCell:(FoodDetailTableViewCell *)foodDetailTableViewCell withImageView:(UIImageView *)modelImg{
    //转化坐标
    //    NSLog(@"%@",modelImg);
    CGPoint startP = [foodDetailTableViewCell convertPoint:modelImg.center toView:self.view.window];
    //创建图画
    UIImageView *imageView = [[UIImageView alloc] initWithImage:modelImg.image];
    imageView.frame = modelImg.bounds;
    imageView.center = startP;
    [self.view.window addSubview:imageView];
    //定义结束点
    CGPoint endP = CGPointMake(self.view.bounds.size.width * 0.61, self.view.bounds.size.height);
    CAAnimationGroup *groupAni = [CAAnimationGroup animation];
    //抛物线
    CAKeyframeAnimation *keyAni = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    //    缩放
    CABasicAnimation *scaleAni = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    scaleAni.toValue = @(0.1);
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:startP];
    //抛物线
    [path addQuadCurveToPoint:endP controlPoint:CGPointMake(startP.x + 50, startP.y - 50)];
    keyAni.path = path.CGPath;
    //    keyAni.duration = 1;
    keyAni.fillMode = kCAFillModeForwards;
    keyAni.removedOnCompletion = NO;
    
    groupAni.delegate = self;
    
    //setValueForkey !!!!!注意:要在添加动画之前做这件事儿
    
    groupAni.animations = @[keyAni,scaleAni];
    groupAni.duration = 1;
    [groupAni setValue:imageView forKey:@"name"];
    
    groupAni.fillMode = kCAFillModeForwards;
    groupAni.removedOnCompletion = NO;
    
    [imageView.layer addAnimation:groupAni forKey:nil];
    
    
}
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    UIImageView * iv = [anim valueForKey:@"name"];
    
    [iv removeFromSuperview];
    
    iv = nil;
    
    
}
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView == self.foodCategroyView) {
        return 0;
    }
    return 30;
    
}
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (tableView == self.foodCategroyView) {
        return nil;
    }
    //创建头视图
    CGFloat headerViewHeight = [self tableView:tableView heightForHeaderInSection:section];
    UIView *headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, tableView.bounds.size.width, headerViewHeight);
    headerView.backgroundColor = [UIColor cz_colorWithHex:0xf8f8f8];
    FoodModel *model = _newsList[section];
    
    UILabel *headerLabel = [UILabel cz_labelWithText:model.name fontSize:14.f color:[UIColor cz_colorWithHex:0x898989]];
    headerLabel.frame = headerView.bounds;
    [headerView addSubview:headerLabel];
    return headerView;
}
//选中cell方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.foodCategroyView) {
        //            self.foodCategroyView.backgroundColor = [
        //判断点击indexpath是否相等
        if (self.leftSelectedIndexPath != indexPath) {
            //修改flag的值
            self.flag = 1;
            //让右边的滑动到 indexPath.row 作为右边的组数
            [self.foodView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:indexPath.row] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            //点击记录的indexpath
            self.leftSelectedIndexPath = indexPath;
        }
    }else{
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        
        
    }
}
//左右联动 滑动右边 左边选中对应的位置
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView == self.foodView) {
        //判断flag
        if (self.flag != 1) {
            //获取可视范围内的indexpath
            NSIndexPath *firstIndexPath = [[self.foodView indexPathsForVisibleRows] firstObject];
            //让左边选中对应的位置
            [self.foodCategroyView selectRowAtIndexPath:[NSIndexPath indexPathForRow:firstIndexPath.section inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
            //滑动的时候记录
            self.leftSelectedIndexPath = [NSIndexPath indexPathForRow:firstIndexPath.section inSection:0];
        }
    }
}
//滑动结束
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    self.flag = 0;
    
}


@end
